package com.willpower.eureka.controller;


import com.alibaba.fastjson.JSONObject;
import com.willpower.eureka.auth.response.Result;
import com.willpower.eureka.entity.SysPassword;
import com.willpower.eureka.pojo.User;
import com.willpower.eureka.service.ISysPasswordService;
import com.willpower.eureka.utils.*;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author wen-yi
 * @since 2021-11-07
 */
@Slf4j
@RestController
@RequestMapping("/passwords")
public class SysPasswordController {
    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private PasswordEncoder passwordEncoder;
    @Autowired
    private ISysPasswordService sysPasswordService;

    @GetMapping
    public JSONObject list(HttpServletRequest request,@RequestParam(defaultValue = "") String query, @RequestParam(defaultValue = "1") Integer pageNum, @RequestParam(defaultValue = "10") Integer pageSize){
        log.info("query: {}, pageNum: {}, pageSize: {}", query,pageNum,pageSize);
        return sysPasswordService.selectPage(getUserId(request),query, pageNum, pageSize);
    }

    @PostMapping
    public Result addSysPassword(HttpServletRequest request, SysPassword sysPassword) throws Exception {
        sysPassword.setOwner(getUserId(request));
        String encKey = redisUtil.get("encKey");
        String decryptPassword = AesUtils.decrypt(sysPassword.getPassword(), encKey);
        sysPassword.setPassword(AESCrypt.encryptByAES(decryptPassword));
        return Result.ok(sysPasswordService.save(sysPassword));
    }

    @GetMapping("/{id}")
    public Result getSysPasswordById(@PathVariable("id") Integer id){
        log.info("id: {}", id);
        return Result.ok(sysPasswordService.getById(id));
    }

    @PutMapping("/{id}")
    public Result updateSysPasswordById(@PathVariable("id") Integer id,SysPassword sysPassword){
        log.info("id: {}, sysPassword: {}", id,sysPassword);
        return Result.ok(sysPasswordService.updateById(sysPassword));
    }

    @DeleteMapping("/{id}")
    public Result deleteSysPasswordById(@PathVariable("id") Integer id){
        log.info("id: {}", id);
        return Result.ok(sysPasswordService.removeById(id));
    }

    @PostMapping("/{id}/phone/{phone}/verifyCode/{verifyCode}")
    public Result getPasswordById(@PathVariable("id") Integer id,@PathVariable("phone") String phone,@PathVariable("verifyCode") String verifyCode){
        log.info("id: {},phone: {}, verifyCode: {}", id,phone,verifyCode);
        String password = null;
        if ("13778729882".equals(phone)){
            password = sysPasswordService.getPasswordById(id, verifyCode);
        }
        return Result.ok(password);
    }

    public Integer getUserId(HttpServletRequest request){
        String authorization = request.getHeader("Authorization");
        String token = authorization.substring(authorization.indexOf("Bearer") + 7);
        Claims body = Jwts.parser()
                // 主要密钥编码
                .setSigningKey("wen-yi".getBytes(StandardCharsets.UTF_8))
                .parseClaimsJws(token)
                .getBody();
        Map<String,Object> user = (Map<String, Object>) body.get("user");
        return (Integer) user.get("id");
    }
}
